package com.ossjk.oa.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.oa.system.entity.Area;
import com.ossjk.oa.system.mapper.AreaMapper;
import com.ossjk.oa.system.service.IAreaService;
import com.ossjk.oa.system.vo.AreaVo;

/**
 * <p>
 * 地区表 服务实现类
 * </p>
 *
 * @author chair
 * @since 2019-02-03
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements IAreaService {
	@Override
	public List<AreaVo> getArea() {
		Wrapper wrapper = Condition.create().orderBy("deep", true).orderBy("id", true);
		List<Area> areas = baseMapper.selectList(wrapper);
		List<AreaVo> results = new ArrayList<AreaVo>();
		for (Area area : areas) {
			if (CommonUtil.isEquals("0", area.getPid())) {
				AreaVo areaVo = new AreaVo();
				areaVo.setId(area.getId());
				areaVo.setName(area.getName());
				areaVo.setChildren(getChildren(areas, area));
				results.add(areaVo);
			}
		}
		return results;
	}

	private List<AreaVo> getChildren(List<Area> areas, Area area) {
		List<AreaVo> children = new ArrayList<AreaVo>();
		for (Area area2 : areas) {
			if (CommonUtil.isEquals(area.getId(), area2.getPid())) {
				AreaVo areaVo2 = new AreaVo();
				areaVo2.setId(area2.getId());
				areaVo2.setName(area2.getName());
				children.add(areaVo2);
				areaVo2.setChildren(getChildren(areas, area2));
				if (area2.getDeep() == 3) {
					areaVo2.setChildren(null);
				}
			}
		}
		return children;
	}

}
